package com.itheima.controller;

import cn.hutool.core.bean.BeanUtil;
import com.itheima.common.Code;
import com.itheima.common.Result;
import com.itheima.pojo.Category;
import com.itheima.pojo.CategoryTest;
import com.itheima.service.CategoryService;
import com.itheima.vo.PagingQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author :WuJunJie
 * packageName :com.itheima.controller
 * fileName :CategoryController
 * creationTime :2022-11-22 11:29
 */
@RestController
@RequestMapping("category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public Result insertCategory(@RequestBody Category category){
        Boolean insert=categoryService.insertCategory(category);
        if (insert){
            return Result.success();
        }
      return Result.error(Code.Unauthorized.getCode());
    }
    @DeleteMapping
    public Result deleteCategory(@RequestParam(name = "id") String id){
        Boolean delete=categoryService.deleteCategory(id);
        if (delete){
            return Result.success();
        }
        return Result.error(Code.Unauthorized.getCode());
    }
    @PutMapping
    public Result updateCategory(@RequestBody Category category){
        Boolean update=categoryService.updateCategory(category);
        if(update){
            return Result.success();
        }
        return Result.error(Code.Unauthorized.getCode());
    }
    @GetMapping("page")
    public Result selectPage(
            @RequestParam(name = "page" ,defaultValue = "1") Integer page,
            @RequestParam(name = "pageSize" ,defaultValue = "2") Integer pageSize){

        PagingQueryVo<Category> categoryPagingQueryVo = categoryService.selectPage( page, pageSize);
        return Result.success(categoryPagingQueryVo);
    }

    @GetMapping("list")
    public Result selectByType(@RequestParam(name = "type")String type){
        List<Category> categories=categoryService.selectByType(type);
        return Result.success(categories);
    }

    @GetMapping("test")
    public Result selectTest(@RequestParam(name = "type")String type){
        List<Category> categories=categoryService.selectByType(type);
        List<CategoryTest> categoryTestsList=new ArrayList<>();
        for (Category category : categories) {
            CategoryTest categoryTest = new CategoryTest();
//            BeanUtils.copyProperties(category,categoryTest);
            BeanUtil.copyProperties(category,categoryTest);
            categoryTestsList.add(categoryTest);
        }
        return Result.success(categoryTestsList);
    }

}
